/**
 *	Written by:Nicholas Hillier Nov. 18 2008
 *  The video display area
*/
package com.ghostmonk.media.video
{
	import com.ghostmonk.events.video.*;
	import com.ghostmonk.model.VideoMetaData;
	
	import flash.display.Sprite;
	import flash.events.*;
	import flash.media.Video;
	import flash.net.*;
	
	[Event (name="stop", type="com.ghostmonk.events.video.NetStreamEvent")]
	[Event (name="start", type="com.ghostmonk.events.video.NetStreamEvent")]
	[Event (name="full", type="com.ghostmonk.events.video.NetStreamEvent")]
	[Event (name="flush", type="com.ghostmonk.events.video.NetStreamEvent")]
	[Event (name="empty", type="com.ghostmonk.events.video.NetStreamEvent")]
	[Event (name="metaInfoReady", type="com.ghostmonk.events.video.MetaInfoEvent")]
	
	public class VideoScreen extends Sprite
	{
		private var _video:Video;
		private var _stream:NetStream;
		private var _connection:NetConnection;
		private var _ratio:Number;
		private var _duration:Number;
		
		public function VideoScreen(smoothing:Boolean = false)
		{
			_connection = new NetConnection();
			_connection.connect(null);
			
			var client:Object = new Object();
			client.onMetaData = onMetaData;
			
			_stream = new NetStream(_connection);
				
			_stream.addEventListener(NetStatusEvent.NET_STATUS, onNetStatus);
			_stream.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
			
			_video = new Video();
			_video.smoothing = true;
			
			_stream.client = client;
			_video.attachNetStream(_stream);
			addChild(_video);
		}
		
		public function get time():Number
		{
			return _stream.time;
		}
		
		public function get duration():Number
		{
			return _duration;
		}
		
		public function get percentLoaded():Number
		{
			return Math.max(0, _stream.bytesLoaded/_stream.bytesTotal);
		}
		
		public function setSize(width:Number, height:Number):void
		{
			_video.width = width;
			_video.height = height;
		}
		
		public function load(url:String, autoPlay:Boolean = true):void
		{
			_stream.play(url);
			if(!autoPlay) _stream.pause();
			_video.visible = true;
		}
		
		public function close():void
		{
			_video.visible = false;
			_stream.pause();
			_video.clear();
		}
		
		public function play():void
		{
			_stream.resume();
		}
		
		public function pause():void
		{
			_stream.pause();
		}
		
		public function seek(offset:Number):void
		{
			_stream.seek(offset);
		}
		
		private function onNetStatus(e:NetStatusEvent):void
		{
            dispatchEvent(new NetStatusEvent(e.info.code));
		}
		
		private function onMetaData(data:Object):void
		{
			_duration = data.duration;
			dispatchEvent(new MetaInfoEvent(MetaInfoEvent.META_INFO_READY, new VideoMetaData(data)));
		}
		
		private function onIOError(e:IOErrorEvent):void
		{
			trace(e.text);
		}
	}
}